extends Control
@onready var rankItemContainer = $Members/VBoxContainer

func _ready():
	GlobalSignals.NM_GET_SCORE_INFO_RESULT.connect(NM_GET_SCORE_INFO_RESULT_handler)
	
	clearRankItems()
	NetMessages.getRankData()


func _exit_tree():
	GlobalSignals.NM_GET_SCORE_INFO_RESULT.disconnect(NM_GET_SCORE_INFO_RESULT_handler)


func NM_GET_SCORE_INFO_RESULT_handler(data):
	updateView(data)
	
	
func clearRankItems():
	for child in rankItemContainer.get_children():
		child.queue_free()


func updateView(data):
	var sortedArr = []
	var scoreInfo:Dictionary = data["scoreInfo"] as Dictionary
	var maxScore = -1
	var maxScoreUserName = ""
	var scoreCount = scoreInfo.keys().size()
	
	for index in range(scoreCount):
		for userName in scoreInfo.keys():
			if scoreInfo[userName] >= maxScore:
				maxScore = scoreInfo[userName]
				maxScoreUserName = userName
		sortedArr.append({
			"userName": maxScoreUserName,
			"score": maxScore
		})
		scoreInfo.erase(maxScoreUserName)
		maxScore = -1
		maxScoreUserName = ""
		
	for scoreItemInfo in sortedArr:
		var inst:RankItem = Global.createSceneInst("RankItem") as RankItem
		rankItemContainer.add_child(inst)
		inst.setScoreInfo(scoreItemInfo)
	

func _on_return_pressed():
	GlobalSignals.PLAY_SOUND.emit(SoundManager.CLICK)
	Global.changeScene("Title")
